package com.webserver.core;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

public class DispatcherServlet {
    private static DispatcherServlet instance = new DispatcherServlet();
    private static File rootDir;
    private static File staticDir;
    static {
        try {
            rootDir = new File(
                    DispatcherServlet.class.getClassLoader().getResource(".").toURI()
            );
            staticDir = new File(rootDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    private DispatcherServlet(){}
    public static DispatcherServlet getInstance(){
        return instance;
    }
    public void service(HttpServletRequest request, HttpServletResponse response){
        String path = request.getRequestURI();
        try {
            Method method = HandlerMapping.getMethod(path);
            if (method!=null){
                Class cls = method.getDeclaringClass();
                Object controllor = cls.newInstance();
                method.invoke(controllor,request,response);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        File file = new File(staticDir,path);
        if (file.isFile()){
            response.setContentFile(file);
            response.addHeader("Server","BirdWebServer");
        }else {
            response.setStatusCode(404);
            response.setStatusReason("NotFound");
            file = new File(staticDir,"/root/404.html");
            response.setContentFile(file);
        }
    }
    
}
